package com.schedule.task.component;

import com.alibaba.fastjson.JSON;
import com.schedule.task.constant.Socket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Slf4j
@Component
public class WebSocketDisconnectListener implements ApplicationListener<SessionDisconnectEvent> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = sha.getSessionId();
        // 在redis去掉
        // 根据sessionId 查出用户id
        String userId = stringRedisTemplate.opsForValue().get(sessionId);
        if (null != userId) {
            stringRedisTemplate.delete(sessionId);
            stringRedisTemplate.delete(Socket.Prefix.USER_PRE_SET+userId);
        }

//        log.info("sessionId: {} 已断开", sessionId); //        log.info(JSON.toJSONString(sha));
    }
}
